package me.zxc.utils;

import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.*;

import java.util.HashMap;

/**
 * @author zhangxucheng
 * @version 1.0
 * @date 2022/2/11 15:04
 */
public class ExcelFormatter {

    /**
     * 自适应列宽最大值，这里为了减少运算以字节数组长度作为单位。
     * 其与列宽之间的关系为：列宽 = 字节数组长度 * 256
     * utf-8 编码的单个汉字占 3 或 4 个字节
     */
    private static final int MAX_LENGTH = 24;

    private static final int SINGLE = 0;

    /**
     * 插入表头 并添加粗体居中样式
     *
     * @param headers 表头数组
     * @param writer  hutool ExcelWriter
     */
    public static void createHeader(String[] headers, ExcelWriter writer) {
        CellStyle cellStyle = writer.createCellStyle();
        Font font = writer.createFont();
        // 粗体
        font.setBold(true);
        cellStyle.setFont(font);
        // 居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        Row headerRow = writer.getOrCreateRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(cellStyle);
        }
        // 跳过当前行（首行） 从下一行开始继续写入数据
        writer.passCurrentRow();
    }

    /**
     * 设置自适应列宽
     *
     * @param writer   hutool ExcelWriter
     * @param autoWrap 超出预设最大长度文本，是否自动换行
     */
    public static void autoSizeColumns(ExcelWriter writer, boolean autoWrap) {
        // 获取总行数与总列数
        int columnNum = writer.getColumnCount();
        int rowNum = writer.getRowCount();
        // 定义超出上限宽度后自动换行样式
        CellStyle cellStyle = writer.createCellStyle();
        cellStyle.setWrapText(true);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        for (int i = 0; i < columnNum; i++) {
            // 每一列遍历所有行 筛选出最长的那个
            HashMap<Integer, Integer> compareMap = new HashMap<>();
            int columnWidth = writer.getSheet().getColumnWidth(columnNum);
            compareMap.put(SINGLE, columnWidth / 256);
            for (int j = 0; j < rowNum; j++) {
                Row curRow = writer.getOrCreateRow(j);
                if (curRow.getCell(i) != null) {
                    Cell curCell = curRow.getCell(i);
                    if (curCell.getCellType().equals(CellType.STRING)) {
                        int length = curCell.getStringCellValue().getBytes().length;
                        compareMap.put(0, Math.max(length, compareMap.get(SINGLE)));
                        if (length > MAX_LENGTH) {
                            compareMap.put(SINGLE, MAX_LENGTH);
                            if (autoWrap) {
                                curCell.setCellStyle(cellStyle);
                            }
                            // 此时已经可以确定列宽就是最大长度 结束循环
                            break;
                        }
                    }
                }
            }
            columnWidth = compareMap.get(SINGLE) * 256;
            writer.getSheet().setColumnWidth(i, columnWidth);
        }
    }
}
